import json
import os.path

from mylog import addLog

languageDict = None
curLanguage = 1


def getCNfromDict(key: str) -> str:
    """
    从语言词条文件中，获取相应语言的，与key对应的词条
    :param key:词条ID
    :return:
    """
    global languageDict
    global curLanguage

    if languageDict == None:
        return ""
    else:
        for d in languageDict:
            if d['key'] == key:
                if curLanguage == 0:
                    return d['chinese']
                elif curLanguage == 1:
                    return d['english']
                else:
                    return ""


def getCurLang() -> int:
    global curLanguage
    return curLanguage


def setCurLang(index, INIPath = './res/syslang.ini'):
    # 使用 'w' 模式打开文件（清空文件内容）
    with open(INIPath, "w", encoding="utf-8") as file:
        file.write(f"{index}")


def loadLangDict(INIPath='./res/language.ini'):
    global languageDict
    try:
        with open(INIPath, 'r', encoding='utf-8') as file:
            languageDict = json.load(file)
            return 0
    except Exception as e:
        addLog('LanguageTool', 'warn', 'read languageDict error!')
        return -1


def loadCurLang(INIPath='./res/syslang.ini'):
    global curLanguage
    if not os.path.exists(INIPath):
        with open(INIPath, 'w', encoding='utf-8') as file:
            file.write('0')
        curLanguage = 0
        addLog('LanguageTool', 'info', f'{INIPath} 不存在，已创建默认设置')
    else:
        with open(INIPath, 'r', encoding='utf-8') as file:
            content = file.read().replace("\n", "").replace("\r", "")
        curLanguage = int(content)
        addLog('LanguageTool', 'info', '当前软件语言为'+content)